package retry;

import com.zwl.dropshipping.dal.bo.DispatchEventRetryLogWxMsgBo;
import com.zwl.dropshipping.dal.model.EventRetryLogModel;

/**
 *告警通知调度入口
 * @author zhangweilin
 * @date 2023/10/13 11:09
 * @Description:
 */
public abstract class RetryResultNoticeHandlerWxDispatch implements RetryResultHandler<EventRetryLogModel> {

	/**
	 * 先按规则调度一下
	 * @param eventRetryLogModel
	 * @param argArr
	 * @param e
	 * @return
	 */
	public DispatchEventRetryLogWxMsgBo dispatch(EventRetryLogModel eventRetryLogModel, Object[] argArr, Throwable e) {
		//重试到多少次则告警, -1表示不告警，默认5次
		Integer retryTimesWarnThreshold = eventRetryLogModel.getRetryTimesWarnThreshold();
		if (retryTimesWarnThreshold < 0) {
			return null;
		}
		Integer retryTimes = eventRetryLogModel.getRetryTimes();
		//还未到告警阈值，则不告警
		if (retryTimes < retryTimesWarnThreshold) {
			return null;
		}

		//连续告警次数
		int continuousWarnCurrentCount = 0;
		//		如果连续告警: 连续告警次数，0表示不限制次数，默认连续告警10次
		Integer continuousWarnMaxCount = eventRetryLogModel.getContinuousWarnMaxCount();
		//是否连续告警
		Boolean continuousWarnFlag = eventRetryLogModel.getContinuousWarnFlag();
		//如果不连续告警
		if (continuousWarnFlag == null || !continuousWarnFlag) {
			//告警过一次后，就不再告警了
			if (retryTimes > retryTimesWarnThreshold) {
				return null;
			}
			//如果是连续告警
		} else {
			int diffRetryTimes = retryTimes - retryTimesWarnThreshold;
			if (diffRetryTimes > 0) {
				//1则表示每次都告警，1的除数为0
				Integer continuousWarnInterval = eventRetryLogModel.getContinuousWarnInterval();
				if (diffRetryTimes % continuousWarnInterval > 0) {
					return null;
				} else {
					continuousWarnCurrentCount = diffRetryTimes / continuousWarnInterval;
					if (null != continuousWarnMaxCount && continuousWarnMaxCount > 0 && continuousWarnCurrentCount > continuousWarnMaxCount) {
						return null;
					}
				}
			} else {
				//首次告警
				continuousWarnCurrentCount = 1;
			}
		}
		DispatchEventRetryLogWxMsgBo dispatchEventRetryLogWxMsgBo = new DispatchEventRetryLogWxMsgBo();
		dispatchEventRetryLogWxMsgBo.setEventRetryLogModel(eventRetryLogModel);
		dispatchEventRetryLogWxMsgBo.setThrowable(e);
		dispatchEventRetryLogWxMsgBo.setRetryTimes(retryTimes);
		dispatchEventRetryLogWxMsgBo.setContinuousWarnCurrentCount(continuousWarnCurrentCount);
		dispatchEventRetryLogWxMsgBo.setContinuousWarnMaxCount(continuousWarnMaxCount);
		return dispatchEventRetryLogWxMsgBo;
	}

}
